<template>
  <el-container id="elmain" style="height:100%;border: none;">
    <el-aside :style="'width:' + (store.state.isOldMenu?'200':side_config.menu_width) + 'px;border: none;background-color: #121733;'">

      <div class="page_box" v-if="!store.state.isOldMenu">
          <!-- ===========================侧边栏============================= -->
        <div @mouseover="side_hover" class="page_side" :style="'width:' + side_config.menu_width + 'px;'">
          <!-- 菜单头 -->
          <div class="page_side_header" :style="'height:' + side_config.side_header_height + 'px'">
            君芒软件
          </div>
          <!-- 菜单主体 -->
          <div class="page_side_main">
            <div class="menubox">
              <div @mouseover.stop="menu_mouseover(menu, index)"
              @mouseleave.stop="menu_mouseleave(menu, index)" 
              @click.stop="menu_click(menu, index)" 
              :style="'height:' + side_config.menu_height + 'px'"
              :class="'jm_menu' + (mouseoverCheck == index?' jm_menu_hover':'')" v-for="(menu, index) in menulist" :key="menu.id">
                <component :is="menu.menuIcon" style="width: 16px;height: 16px;margin-right: 5px;flex-shrink: 0;"></component>
                {{ menu.menuName }}
              </div>
            </div>
          </div>
          <!-- 菜单底部 -->
          <div class="page_side_footer"></div>
        </div>
      
      </div>

      <jm-menu v-else :menuList="menulist" :isCollapse="isCollapse"></jm-menu>

    </el-aside>
    <el-container style="border: none;">
      <el-header style="padding: 0;height: 60px;border: none;background-color: #F1F4FB;">
        <!-- 主体header -->
        <div class="page_main_header">
          <div style="flex-grow: 1;">
            <div @click="testfun()" style="font-size: 15px;font-weight: bold;">啥系统名自己写</div>
          </div>

          <el-dropdown>
            <div style="cursor: pointer;">
              用户名
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <div @click="editPasswordFun()"><el-dropdown-item icon="el-icon-key">修改密码</el-dropdown-item></div>
                <div @click="gotohtml('/')"><el-dropdown-item icon="el-icon-switch-button">退出登录</el-dropdown-item></div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-main v-if="store.state.isOldRouter" style="padding:0 10px 10px 10px;border: none;background-color: #F1F4FB;">
        <router-view />
      </el-main>
      <el-main v-else style="padding:0;border: none;overflow: auto;">
        <router-view v-if="!store.state.menuTabs.length"></router-view>
        <el-tabs
          v-else
          class="diytabs"
          v-model="store.state.menuTabs_active"
          type="border-card"
          closable
          style="background-color: #fff;"
          @tab-change="tabChange"
          @tab-remove="tabRemove"
        >
          <el-tab-pane
            v-for="item in store.state.menuTabs"
            :key="item.name"
            :label="item.title"
            :name="item.name"
          >
            <el-main :style="'padding:0 10px 10px 10px;border: none;height:'+store.state.tab_panel_height+'px;'" v-show="(item.name==store.state.menuTabs_active) && endResize">
              <component :is="item.componentUrl"></component>
            </el-main>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <el-dialog title="修改密码" v-model="openDialog" top="50px">
      <el-form :model="userinfoForm" :rules="rules">
        <el-form-item label="用户名" label-width="120px" prop="userName">
          <el-input readonly v-model="userinfoForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="原密码" label-width="120px" prop="oldPassword">
          <el-input type="password" v-model="userinfoForm.oldPassword" autocomplete="new-password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" label-width="120px" prop="password">
          <el-input type="password" v-model="userinfoForm.password" autocomplete="new-password"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" label-width="120px" prop="repassword">
          <el-input type="password" v-model="userinfoForm.repassword" autocomplete="new-password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="openDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitUserInfo(userinfoForm)" :loading="issubmitUserInfo">确 定</el-button>
        </div>
      </template>
    </el-dialog>




    
    <!-- ============================================================================================== -->
    <div v-show="side_config.isshow" 
      class="jm_menu_children" :style="'left:' + 
      (side_config.menu_width + 1) + 'px;top:' + 
      side_config.pop_top + 'px;'"
      @mouseleave="children_leave()" id="show_pop_box">
      <div class="second_children" v-for="(menu, index) in menu_children" :key="menu.id">
        <div @click.stop="gotoUrl(menu)"
        @mouseover="children_hover(index)" class="second_children_title">
          {{ menu.menuName }}
        </div>
        <div @click.stop="gotoUrl(item)" class="third_children" v-for="(item) in menu.children" :key="item.id">
          {{ item.menuName }}
        </div>
      </div>
    </div>
    <!-- ============================================================================================== -->

  </el-container>
</template>

<script setup>
  import { reactive, ref, onMounted, inject, nextTick, provide } from 'vue'
  import { useRouter } from 'vue-router'
  // import menuJson from './frame.json'
  import JmMenu from '../../components/Jm_Menu/Menu.vue'
  import { useStore } from 'vuex'

  const store = useStore()
  const router = useRouter()
  const $utils = inject('$utils')
  const init_main_scroll = ref(0)
  const timmer = ref(null)
  // // 是否使用默认菜单
  // const isOldMenu = ref(true)
  // // 是否使用默认页面跳转
  // const isOldRouter = ref(false)
  const endResize = ref(true)

  // // 标签页属性
  // const menuTabs = ref(store.state.menuTabs)
  // const activeMenuTabs = ref('')

  const validRenewPSD = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请确认新密码'))
    } else {
      if (userinfoForm.password != '') {
        if (userinfoForm.password != userinfoForm.repassword) {
          callback(new Error('与新密码不一致'))
        }
      }
      callback()
    }
  }

  const openDialog = ref(false)
  const menulist = ref()
  const isCollapse = ref(false)

  const rules = reactive({
    oldPassword: [{required: true, message: '请输入密码', trigger: 'blur'}],
    password: [{required: true, message: '请输入新密码', trigger: 'blur'}],
    repassword: [{required: true, validator: validRenewPSD, trigger: 'blur'}]
  })

  const userinfoForm = reactive({
    userName: '',
    oldPassword: '',
    password: '',
    repassword: ''
  })

  const onMountedHook = function () {
    initPageData()
    windowChange()
    menulist.value = [{
      "id": "0",
      "menuName": "模板页",
      "path": "/admin/modal",
      "menuIcon": "HomeFilled"
    }, {
      "id": "1",
      "menuName": "订单管理",
      "path": "/admin/order",
      "menuIcon": "HomeFilled"
    }, {
      "id": "2",
      "menuName": "新模板页",
      "path": "/admin/modal2_0",
      "menuIcon": "HomeFilled"
    }]
  }
  function initPageData() {
    init_main_scroll.value = document.querySelector('#elmain').scrollHeight
    const body_height = document.querySelector('body').clientHeight
    store.commit('set_body_height', body_height)
  }
  function windowChange() {
    window.onclick = () => {
      return (() => {
        store.commit('set_pop_attr', {
          pop_show: false
        })
      })()
    }
    window.onresize = () => {
      endResize.value = false
      if (timmer.value != null) {
        clearTimeout(timmer.value)
      }
      timmer.value = setTimeout(() => {
        return (() => {
          initPageData()
          store.commit('set_pop_attr', {
            pop_show: false
          })
          endResize.value = true
        })()
      }, 200)
    }
  }
  function gotohtml (url) {
    router.push({path: '/'})
    $utils.cookies.set('token', '')
    // $utils.post({
    //   url: '',
    //   params: userinfoForm,
    //   confirm: true,
    //   confirmText: '是否退出登录？',
    //   ok: function (data) {
    //     router.push({path: '/'})
    //     $utils.cookies.set('token', '')
    //   }
    // })
  }
  function editPasswordFun() {
    userinfoForm.userName = $utils.cookies.get('username')
    userinfoForm.oldPassword = ''
    userinfoForm.password = ''
    userinfoForm.repassword = ''
    openDialog.value = true
  }
  function submitUserInfo() {
    console.log(userinfoForm)
  }
  function testfun() {
    router.push({ path: '/admin' })
  }


  // ====================================================================================
  // 菜单列表
  const side_config = reactive({
    menu_height: 53,
    side_header_height: 50,
    menu_width: 139,
    pop_top: 0,
    isshow: false
  })
  const menu_children = ref([])
  const mouseoverCheck = ref(404)
  const second_menu_index = ref(0)
  function menu_mouseover(item, index) {
    menu_children.value = item.children
    mouseoverCheck.value = index
    const top_height = side_config.menu_height * index + side_config.side_header_height
    const menu_scroll = document.querySelector('.menubox').scrollTop
    side_config.pop_top = top_height - menu_scroll
    side_config.isshow = true
    nextTick(function () {
      const show_pop_box = document.querySelector('#show_pop_box').offsetHeight
      if ((side_config.pop_top + show_pop_box) > init_main_scroll) {
        var temp_height = init_main_scroll - side_config.pop_top - side_config.menu_height
        if (temp_height >= 0) {
          temp_height = 0
        }
        side_config.pop_top = top_height - menu_scroll - show_pop_box + side_config.menu_height + temp_height
      } else {
        side_config.pop_top = top_height - menu_scroll
      }
      
    })
  }
  // 菜单鼠标离开事件
  function menu_mouseleave(item, index) {
    if (mouseoverCheck.value != index) {
      side_config.isshow = false
    }
  }
  // 菜单鼠标点击事件
  function menu_click(item, index) {
    store.commit('set_pop_attr', {
      pop_show: false
    })
    if (!item.children || item.children.length == 0) {
      router.push({path: item.path})
    }
  }
  // 鼠标经过菜单页
  function side_hover() {
    side_config.isshow = false
    mouseoverCheck.value = 404
  }
  // 鼠标经过子节点
  function children_hover(index) {
    second_menu_index.value = index
  }
  // 鼠标离开子节点
  function children_leave() {
    side_config.isshow = false
  }
  // 页面跳转
  function gotoUrl(item) {
    store.commit('set_pop_attr', {
      pop_show: false
    })
    if (!item.children || item.children.length == 0) {
      side_config.isshow = false
      if (item.path.indexOf('?') >= 0) {
        var obj = {}
        var pathDatas = item.path.split('?')[1]
        if (pathDatas.indexOf('&') >= 0) {
          var querys = pathDatas.split('&')
          for (let i = 0; i < querys.length; i++) {
            obj[querys[i].split('=')[0]] = querys[i].split('=')[1]
          }
        } else {
          obj[pathDatas.split('=')[0]] = pathDatas.split('=')[1]
        }
        router.push({path: item.path, query: obj})
      } else {
        router.push({path: item.path})
      }
    } else {

    }
  }
  // ====================================================================================

  // Tab页转换操作 
  function tabChange(val) {
    const findpath = store.state.menuTabs.find(item => item.name == val).path
    router.push(findpath)
    store.commit('set_menuTabs_active', val)
  }
  // Tab页删除操作
  function tabRemove(val) {
    $utils.messageBox.confirm('提示', '是否删除该标签页', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      if (store.state.menuTabs.length == 1) {
        router.push('/admin')
      }
      store.commit('remove_menuTabs', val)
    }).catch((e) => {
      console.log(e)
    })
  }

  onMounted(() => {
    onMountedHook()
  })

</script>

<style scoped>
@import url('./frame.css');
.el-menu-vertical-demo:not(.el-menu--collapse) {
  /* width: unset; */
  width: 200px;
  /* min-height: 400px; */
}
ul{
  padding: 0;
  margin: 0;
  list-style-type: none;
}
.el-aside{
  width: 120px;
  height: 100%;
}
.headercss{
  padding:0;
  height:60px;
  background: -webkit-linear-gradient(left, #101834 , #3C4875); /* Safari 5.1 - 6.0 */
  background: -o-linear-gradient(right, #101834, #3C4875); /* Opera 11.1 - 12.0 */
  background: -moz-linear-gradient(right, #101834, #3C4875); /* Firefox 3.6 - 15 */
  background: linear-gradient(to right, #101834 , #3C4875); /* 标准的语法 */
  display: flex;
  align-items: center;
}
.diyaside{
  background-color: #101834;
}
.el-aside::-webkit-scrollbar{
  display: none;
  width: 0 !important;
  -ms-overflow-style: none;
  overflow: -moz-scrollbars-none;
}
.diytabs >>> .el-tabs__content{
  padding: 10px 0 0 0 !important;
}
</style>
